/*
 * message_service.cpp
 *
 *  Created on: 2008-12-2
 *      Author: fanliangliang
 */

#include "message_service.h"
#include "short_message.h"
#include "toxic.h"

using namespace toxic;

MessageService::MessageService()
:_smsInterface()
,_server()
,_port(0) {

}

MessageService::~MessageService() {

}

bool MessageService::send(const ShortMessage& message) {
	if (message.phoneNumberCount() == 0) {
		return false;
	}

	char httpRequest[4096] = { 0 };
	size_t headLength =
		snprintf(httpRequest, sizeof(httpRequest),
			"POST %s HTTP/1.1\r\n"
			"Accept: */*\r\n"
			"Connection: close\r\n"
			"Host: %s\r\n"
			"Content-Length: %u\r\n\r\n",
			_smsInterface.c_str(),
			_server.c_str(),
			message.packageLength());

	size_t contentLength = message.package(httpRequest + headLength, sizeof(httpRequest) - headLength);
	if (contentLength == 0) {
		return false;
	}

	try {
		TcpSocket socket;
		socket.connect(_server, _port);
		socket.send(httpRequest, headLength + contentLength);

		char httpResponse[1024] = { 0 };
		size_t responseLength = socket.receive(httpResponse, sizeof(httpResponse));

		if (responseLength == 0) {
			return false;
		}

		char* pos = strchr(httpResponse, ' ') + 1;
		string status(pos, 3);
		if (status != "200") {
			return false;
		}

		pos = strstr(httpResponse, "Content-Length") + 15;
		size_t bodyLength = lexical_cast<size_t>(trim(pos, "\r\n "));

		pos = strstr(httpResponse, "\r\n\r\n") + 4;

		return message.unpackage(pos, bodyLength);
	}
	catch (const exception& e) {
		return false;
	}
}

void MessageService::setSmsInterface(const string& smsInterface) {
	_smsInterface = smsInterface;
}

void MessageService::setServer(const string& server) {
	_server = server;
}

void MessageService::setPort(uint16_t port) {
	_port = port;
}

const string& MessageService::smsInterface() const {
	return _smsInterface;
}

const string& MessageService::server() const {
	return _server;
}

uint16_t MessageService::port() const {
	return _port;
}
